<?php

class Admin_AuthController extends Zend_Controller_Action
{

    public function init()
    {
        $this->view->baseUrl = $this->_request->getBaseUrl();
    }

    public function indexAction()
    {
        $storage = new Zend_Auth_Storage_Session();
        $formData = $storage->read();
        if (!$formData){
        	$this->_redirect('Admin/auth/login');
        }
        $this->view->username = $formData->username;
        $this->_redirect('admin/index/index');
    }

    public function loginAction()
    {
        $user = new Admin_Model_DbTable_Users();
        $form = new Admin_Form_Auth_Login();
       	$this->view->form = $form;
       
       	if ($this->getRequest()->isPost()){
       		if ($form->isValid($_POST)){
       			$formData = $form->getValues();
       			
       			$auth = Zend_Auth::getInstance();
       			
       			$authAdapter = new Zend_Auth_Adapter_DbTable($user->getAdapter(),'users');
       			
       			$authAdapter->setIdentityColumn('username')
       						->setCredentialColumn('password');
       		
       			$authAdapter->setIdentity($formData['username']);
       			$authAdapter->setCredential($formData['password']);

       			$result = $auth->authenticate($authAdapter);

       			if ($result->isValid()){
       				$storage = new Zend_Auth_Storage_Session();
       				$CurrentUser = $authAdapter->getResultRowObject();
       				$CurrentUser->isAdmin = true;
       				$storage->write($CurrentUser);
       				$this->_redirect('admin/auth/index');
       			} else {
       				$this->view->errorMessage = "Username ou password invalid, Veuillez réessayer encore.";
       			}
       		}
       	}
    }

    public function logoutAction()
    {
        $storage = new Zend_Auth_Storage_Session();        
        $storage->clear();
        $this->_redirect('admin/auth/login');
    }


}





